#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
const OptionParser = require('brisket/lib/optparse');
const {fgets, getVersion, awk, pad} = require('./utils.js');

var category;
var var_suffix;
var file;
var filter_prefix;
var filter_suffix;
var version;

function loadUnicodeData () {
	var content = awk(
		`${__dirname}/ucd/${file}`,
		new RegExp(`${filter_prefix}${category}${filter_suffix}`),
		(line, re) => line.split(';')[0]
	);
	return content.split('\n');
}

function generate (lines) {
	var buf = [];
	var initial = '';
	var tmp = initial;

	buf.push(`// ${category} letters in ${file} of Unicode ${version}`);
	buf.push(`// generated by "src/unicode-tools/${path.basename(__filename)} ${process.argv[2]}"`);
	buf.push(`const REGEX_${var_suffix.toUpperCase()} = new RegExp('[\\`);

	if (category == 'Zs') {
		lines.unshift('0009');
	}

	for (var i = 0; i < lines.length; i++) {
		var cp = lines[i].split('..').map(s => s.replace(/^\s+|\s+$/g, ''));;
		if (cp[0].length > 4) continue;
		if (cp.length == 2 && parseInt(cp[0], 16) + 1 == parseInt(cp[1], 16)) {
			lines.splice(i + 1, 0, cp.pop());
		}
		var fragment = '\\\\u' + cp.join('-\\\\u');
		if ((tmp + fragment + '\\').length >= 80) {
			buf.push(tmp + '\\');
			tmp = initial + fragment;
		}
		else {
			tmp += fragment;
		}
	}
	if (tmp != initial) {
		buf.push(tmp + '\\');
	}
	buf.push("]');");
	buf.push('');

	buf = buf.map((line, i) => line.replace(/    /g, '\t'));
	console.log(buf.join('\n'));
}

function printHelp () {
	if (file == undefined) {
		console.log('usage: --general-category=<Unicode General Category>');
		console.log('       --prop-list=<Unicode Prop List>');
		process.exit(1);
	}
}

(new OptionParser)
	.on('--general-category  Unicode general category name', v => {
		category = v;
		var_suffix = v;
		file = 'UnicodeData.txt';
		filter_prefix = filter_suffix = ';';
	})
	.on('--prop-list         Unicode prop list name', v => {
		category = v;
		var_suffix = v;
		file = 'PropList.txt';
		filter_prefix = '; ';
		filter_suffix = ' #';
		if (category == 'Sentence_Terminal') {
			var_suffix = 'STerm';
		}
		else if (category == 'Terminal_Punctuation') {
			var_suffix = 'PTerm';
		}
	})
	.parse(process.argv);

getVersion()
.then(ver => version = ver)
.then(printHelp)
.then(loadUnicodeData)
.then(generate)
.catch(error => console.error(error));
